package com.anxin.act.task.service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.anxin.act.task.complete.TaskComplete;
import com.anxin.act.task.dao.WfActHiCommentDao;
import com.anxin.act.task.entity.ViewHiTask;
import com.anxin.act.task.entity.WfActHiComment;
import com.anxin.act.task.entity.WfActHiTask;
import com.anxin.act.task.entity.WfActRuTask;
import com.anxin.act.task.vo.FormPropertyVo;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActTaskUtils;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.DateUtils;
import com.anxin.common.utils.StringUtils;
import com.anxin.common.utils.sys.RoleUtils;
import com.anxin.common.utils.sys.UserUtils;
import com.anxin.framework.web.service.BaseService;
import com.anxin.common.utils.SecurityUtils;
import com.anxin.sys.system.entity.SysUser;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;

/**
 * 加签任务审批记录Service业务层处理
 *
 * @author jbs
 * @date 2021-10-22
 */
@Service
public class WfActHiCommentService extends BaseService<WfActHiCommentDao, WfActHiComment>{
    @Autowired
    private WfActHiCommentDao wfActHiCommentDao;

    @Autowired
    private TaskService taskService;

    @Autowired
    private WfActRuTaskService wfActRuTaskService;

    @Autowired
    private TaskComplete taskComplete;

    /**
     * 查询审批意见
     * @param viewHiTask
     * @return
     */
    public List<WfActHiComment> getCommentList(ViewHiTask viewHiTask){
        List<WfActHiComment> resList = new ArrayList<>();
        if (this.checkCommentPermissions(viewHiTask)){
            if ("actTask".equals(viewHiTask.getType()) && !"comment".equals(viewHiTask.getSourceType())){
                List<Comment> taskComments = taskService.getTaskComments(viewHiTask.getId());
                for (Comment taskComment : taskComments) {
                    WfActHiComment wfActHiComment = new WfActHiComment(taskComment);
                    resList.add(wfActHiComment);
                }

            }else {
                resList = wfActHiCommentDao.findList(new WfActHiComment(viewHiTask.getId()));
            }
        }else {
            if (viewHiTask.getApprovalTime() != null){
                WfActHiComment wfActHiComment = new WfActHiComment();
                wfActHiComment.setMessage("***");
                resList.add(wfActHiComment);
            }
        }


        return resList;
    }

    /**
     * 查询当前用户是否有查询这个节点审批意见的权限
     * @param viewHiTask
     * @return
     */
    private boolean checkCommentPermissions(ViewHiTask viewHiTask){
        HistoricTaskInstance hiTask = ActTaskUtils.getHiTask(viewHiTask.getTaskId());
        if (hiTask != null){
            ActivityImpl activityImpl = ActUtils.getActivityImpl(hiTask.getProcessDefinitionId(),hiTask.getTaskDefinitionKey());
            if (activityImpl.getProperties().get("viewcommentrole") != null){
                String[] viewCommentRoles = activityImpl.getProperties().get("viewcommentrole").toString().split(",");
                JSONArray viewCommentRoleArray = (JSONArray)  JSONArray.toJSON(viewCommentRoles);
                return RoleUtils.currentUserRoleByKey(viewCommentRoleArray);
            }
        }

        return true;
    }



    /**
     * 获取任务历史
     * @param taskVo
     */
    public WfActHiTask getHiTask(TaskVo taskVo){
        return this.getHiTask(taskVo,"comment");
    }

    /**
     * 获取任务历史
     * @param taskVo
     */
    @Transactional(readOnly = false)
    public WfActHiTask getHiTask(TaskVo taskVo,String sourceType){
        if ("actTask".equals(taskVo.getViewRuTask().getType())){
            return new WfActHiTask(taskVo.getTaskId(),sourceType,taskVo.getViewRuTask().getType());
        }else {
            WfActRuTask wfActRuTask = wfActRuTaskService.get(taskVo.getId());
            return new WfActHiTask(wfActRuTask,sourceType,taskVo.getViewRuTask().getType());
        }
    }

//    /**
//     * 暂存审批意见
//     * @param taskVo taskVo
//     */
//    public void stagingComment(TaskVo taskVo){
//        if ("actTask".equals(taskVo.getTaskType())){
//            taskComplete.addCommentByFiled(taskVo);
//        }else {
//            this.addComment(taskVo,taskVo.getId());
//        }
//
//    }

    /**
     * 添加审批意见
     * @param actId 流程实例ID
     * @param taskId 待办任务ID
     * @param comment 审批意见
     */
    @Transactional(readOnly = false)
    public void addComment(String actId,String taskId,String comment){
        WfActHiComment  wfActHiComment = new WfActHiComment(taskId,actId,comment);
        SysUser user = UserUtils.getUser();

        wfActHiComment.setUserId(user.getId());
        wfActHiComment.setUserName(user.getUserName());
        wfActHiComment.setTime(new Date());

        super.save(wfActHiComment);

    }

    /**
     * 设置前加签和转签的审批意见
     */
    @Transactional(readOnly = false)
    public void addAddTaskComment(TaskVo taskVo,String taskId){
        if (StringUtils.isNotBlank(taskVo.getAddTaskRemark())){

            SysUser user = UserUtils.getUser();
            String userName = user.getUserName();
            String userId = user.getId();

            WfActHiComment wfActHiComment = new WfActHiComment(taskId, taskVo.getActId(), "备注:"+taskVo.getAddTaskRemark());
            wfActHiComment.setUserId(userId);
            wfActHiComment.setUserName(userName);
            wfActHiComment.setTime(DateUtils.getNowDate());
            super.save(wfActHiComment);
        }
    }


    /**
     * 设置审批意见
     * @param taskVo 待办任务对象
     * @param taskId 任务ID
     */
    @Transactional(readOnly = false)
    public void addComment(TaskVo taskVo,String taskId){
        List<FormPropertyVo> formFiledList = taskVo.getFormFieldList();
        SysUser user = UserUtils.getUser();
        String userName = user.getUserName();
        String userId = user.getId();

        for (FormPropertyVo formPropertyVo : formFiledList) {
            StringBuffer comment = new StringBuffer(formPropertyVo.getName()+":"+(StringUtils.isNotBlank(formPropertyVo.getValueText())?formPropertyVo.getValueText():"无"));
            WfActHiComment wfActHiComment = new WfActHiComment(taskId, taskVo.getActId(), comment.toString());
            wfActHiComment.setUserId(userId);
            wfActHiComment.setUserName(userName);
            wfActHiComment.setTime(DateUtils.getNowDate());
            super.save(wfActHiComment);
        }

    }

    /**
     * 查询加签任务审批记录
     *
     * @param id 加签任务审批记录ID
     * @return 加签任务审批记录
     */
    public WfActHiComment getById(String id){
        return wfActHiCommentDao.getById(id);
    }

    /**
     * 查询加签任务审批记录列表
     *
     * @param wfActHiComment 加签任务审批记录
     * @return 加签任务审批记录
     */
    public List<WfActHiComment> findList(WfActHiComment wfActHiComment){
        return wfActHiCommentDao.findList(wfActHiComment);
    }



    /**
     * 保存加签任务审批记录
     *
     * @param wfActHiComment 加签任务审批记录
     * @return 结果
     */
    public int save(WfActHiComment wfActHiComment){
        return super.save(wfActHiComment);
    }


    /**
     * 删除加签任务审批记录信息
     *
     * @param id 加签任务审批记录ID
     * @return 结果
     */
    public int deleteById(String id){
        SysUser user = SecurityUtils.getUser();
        return wfActHiCommentDao.deleteById(id,user.getId());
    }

    /**
     * 查询补充意见
     */
    public WfActHiComment findSupplementaryComment(String taskId,String actId){
        return wfActHiCommentDao.findSupplementaryComment(taskId,actId);
    }

}
